package com.googlecode.chamerling.blog.petals.router;

import java.util.Date;
import java.util.Map;

import org.objectweb.fractal.fraclet.annotation.annotations.FractalComponent;
import org.objectweb.fractal.fraclet.annotation.annotations.Interface;
import org.objectweb.fractal.fraclet.annotation.annotations.LifeCycle;
import org.objectweb.fractal.fraclet.annotation.annotations.Monolog;
import org.objectweb.fractal.fraclet.annotation.annotations.Provides;
import org.objectweb.fractal.fraclet.annotation.annotations.type.LifeCycleType;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.petals.jbi.component.context.ComponentContext;
import org.ow2.petals.jbi.messaging.endpoint.ServiceEndpoint;
import org.ow2.petals.jbi.messaging.exchange.MessageExchange;
import org.ow2.petals.jbi.messaging.routing.RoutingException;
import org.ow2.petals.jbi.messaging.routing.module.ReceiverModule;
import org.ow2.petals.jbi.messaging.routing.module.SenderModule;
import org.ow2.petals.transport.util.TransportSendContext;
import org.ow2.petals.util.LoggingUtil;

@FractalComponent
@Provides(interfaces = {
		@Interface(name = "logSender", signature = SenderModule.class),
		@Interface(name = "logReceiver", signature = ReceiverModule.class) })
public class LogModule implements SenderModule, ReceiverModule {

	@Monolog(name = "logger")
	private Logger logger;

	private LoggingUtil log;

	/**
	 * {@inheritDoc}
	 */
	public void electEndpoints(
			Map<ServiceEndpoint, TransportSendContext> electedEndpoints,
			ComponentContext sourceComponentContext, MessageExchange exchange)
			throws RoutingException {
		this.log.info(LogModule.class.getCanonicalName()
				+ " router module is sending a message exchange with ID = "
				+ exchange.getExchangeId() + " at " + new Date());

		for (ServiceEndpoint endpoint : electedEndpoints.keySet()) {
			this.log.info("Selected endpoint : " + endpoint.getEndpointName());
		}

		// Do what you want...
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean receiveExchange(MessageExchange exchange,
			ComponentContext sourceComponentContext) throws RoutingException {
		this.log.info(LogModule.class.getCanonicalName()
				+ " router module is receiving a message exchange with ID = "
				+ exchange.getExchangeId() + " at " + new Date());
		// Do what you want...
		return false;
	}

	@LifeCycle(on = LifeCycleType.START)
	protected void start() {
		this.log = new LoggingUtil(this.logger);
		this.log.debug("Starting...");
	}

	@LifeCycle(on = LifeCycleType.STOP)
	protected void stop() {
		this.log.debug("Stopping...");
	}

}
